package com.example.demo.outlook.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

public class JwtUtil {

    private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public static String createJwt(String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .setIssuer("myApp")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1小时过期
                .signWith(key)
                .compact();
    }

    public static Long parseJwt(String jwt) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(jwt);

            Claims claims = claimsJws.getBody();
            claims.getId();
            System.out.println("Subject: " + claims.getSubject());
            System.out.println("Issuer: " + claims.getIssuer());
            System.out.println("Expiration: " + claims.getExpiration());

            return Long.valueOf(claims.getId());
        } catch (Exception e) {
            System.out.println("JWT无效: " + e.getMessage());
            return 0L;
        }

        //return 1;
    }

}
